/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { Alert, Button } from 'antd';
import { pickedLineData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { ctx2 } from '@app-cad/module';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useState } from 'react';
import { usePlaneContext } from './PlaneContext';
import { ChildPlaneCommandProps } from './types';

type FormData = {
  line?: pickedLineData;
  point?: pickedVertexData;
};

type Params = {
  mode: 'point-line';
  line: string;
  point: string;
};

export const PlanePointLine = ({
  props,
  onClose,
  editDxid,
}: ChildPlaneCommandProps) => {
  const [formData, setFormData] = useState<FormData>({});
  const { sharedPoint, setSharedPoint, sharedLine, setSharedLine } =
    usePlaneContext();

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({});
      return;
    }

    const { line, point } = props.params as Params;

    await initEditDependency([line, point]);

    const pointObj = picker.generatePickObjByPickID(point) as pickedVertexData;
    const lineObj = picker.generatePickObjByPickID(line) as pickedLineData;

    setFormData({
      point: pointObj,
      line: lineObj,
    });

    setSharedPoint(pointObj);
    setSharedLine(lineObj);
  }, [editDxid]);

  useEffect(() => {
    if (sharedPoint && !formData.point) {
      setFormData((prev) => ({ ...prev, point: sharedPoint }));
    }
    if (sharedLine && !formData.line) {
      setFormData((prev) => ({ ...prev, line: sharedLine }));
    }
  }, [sharedPoint, sharedLine]);

  const isFormDataValid = () => {
    const { line, point } = formData;

    return line != null && point != null;
  };

  useAsyncEffect(async () => {
    clear();

    if (isFormDataValid()) {
      await execute(true);
    }

    ctx2.viewer.requestRender();
  }, [formData]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-plane-point-line', {
      commandName: 'CreatePlane',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const { line, point } = formData;

    return confirmCommand(
      {
        a: {
          mode: 'point-line',
          line: line.edgeId,
          point: point.vertexId,
        },
      },
      preview,
    );
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      line: {
        type: 'string',
        format: PickInputRJSFFormat.PickLine,
      },
      point: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      onCancel={onClose}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        if (v.point && v.point !== formData.point) {
          setSharedPoint(v.point);
        }
        if (v.line && v.line !== formData.line) {
          setSharedLine(v.line);
        }

        setFormData(v);
      }}
      extraUiSchema={{
        line: {
          'ui:placeholder': '请输入直线',
          'ui:autofocus': true,
        },
        point: {
          'ui:placeholder': '请输入通过点',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
};
